import {defineStore} from "pinia";
import {setToken, } from "~/utils/cookie";
import {login, emailCodeLogin, register} from "~/api/user";
import type { BlogLoginForm,  BlogRegisterForm} from "~/api/user/types";

export const useUserStore = defineStore("user", () => {
    const doLogin = async (data: BlogLoginForm, loginType: string) => {
        let resData;
        if (loginType == "pwdLogin") {
            resData = await useAsyncData("pwdLogin", () => login(data));
        } else {
            resData = await useAsyncData("emailCodeLogin", () =>
                emailCodeLogin(data)
            );
        }
        const {data: res} = resData;
        const token = (res.value as ApiResponse).data.token;
        setToken(token)
        return resData;
    }

    const doRegister = async (data: BlogRegisterForm) => {
        const {data: res} = await useAsyncData("register", () => register(data));
        const token = (res.value as ApiResponse).data.token;
        setToken(token)
        return res;
    }

    return {doLogin, doRegister};
});
